var url = "http://47.108.197.28:8000/city";
var nameList = [];
var list = [];
$.ajax({
    url,
    success:res=>{
        var hotCities = res.data.hotCities;
        hotCities.forEach(item=>{
            var{name} = item;
            temple = `
                <button>${name}</button>
            `
            $(".hot").append(temple);
        })
        var cities = res.data.cities;
        for(key in cities){
            $(".city").append(`<p class="spell" id="${key}">${key}</p>`);
            $("aside").append(`<a href="#${key}">${key}</a>`);
            cities[key].forEach(item=>{
                var {name} = item;
                nameList.push(name);
                $(".city").append(`<p class="cityName">${name}</p>`);
            })
        }
        $("#search").keydown(function(event){
            if(event.keyCode == 13){
                add($(this).val());
                $(this).val("");
            }
        })

        $("button,.cityName").click(function(){
            add($(this).html());
        })
        
        //自动搜索函数
        function add(value){
            if(value && nameList.includes(value)){
                if(!list.includes(value)){
                    list.unshift(value);
                    $(".historical_item").prepend(`
                        <button class = "btn">${value}</button>
                    `);
                }else{
                    var index = list.indexOf(value);
                    var del = list.splice(index,1);
                    list.unshift(...del);
                    $(".historical_item button").eq(index).remove();
                    $(".historical_item").prepend(`
                        <button class = "btn">${del}</button>
                    `)
                }
            }
            $(".btn").click(function(){
                add($(this).html());
            })
            console.log(list);
        }
        
        
    }
})

